﻿using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtilsDll.Utils.Currency.TextUtils;
using CatUtilsDll.Utils.Currency.WebUtils;
using System;

namespace CatUtils.Utils.SpecialUtils.ContentHelper.MoeWiki
{
    internal class MoeWikiHelper
    {
        /// <summary>
        ///搜索API
        /// </summary>
        public static string SearchAPI = "https://zh.moegirl.org/index.php?search={0}&title=Special:%E6%90%9C%E7%B4%A2&profile=default&fulltext=1";

        /// <summary>
        /// 域名
        /// </summary>
        public static string Domain = "https://zh.moegirl.org";

        /// <summary>
        ///搜索并返回内容 并且指定获取文章简介的长度。
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="ContentLength">文章超出长度被截断</param>
        /// <returns></returns>
        public static string Search(string Tag, int ContentLength)
        {
            return TextHelper.Substring(Search(Tag), ContentLength);
        }

        /// <summary>
        /// 搜索并返回内容
        /// </summary>
        /// <param name="Tag"></param>
        /// <returns></returns>
        public static string Search(string Tag)
        {
            string WebAPI = string.Format(SearchAPI, Transcoding.UrlEncode(Tag));
            Console.WriteLine(WebAPI);
            string Shtml = WebHelper.HttpPcGet(WebAPI);
            string WikiLink = HtmlHelper.GetFirstLink(Shtml, "//p[@class='mw-search-exists']/strong/a");
            string Content = GetWiki(WikiLink);
            return Content;
        }

        /// <summary>
        /// 获取维基百科
        /// </summary>
        /// <param name="WikiLink"></param>
        /// <returns></returns>
        private static string GetWiki(string WikiLink)
        {
            if (WikiLink == "")
                return "";
            Console.WriteLine(Domain + WikiLink);
            string Shtml = WebHelper.HttpPcGet(Domain + WikiLink);

            return ContentClear(Shtml);
        }

        public static string ContentClear(string Shtml)
        {
            Shtml = HtmlHelper.GetFirstHtml(Shtml, "//div[@id='mw-content-text']");

            Shtml = HtmlHelper.RemoveNode(Shtml, "//div[starts-with(@class,'infoBox')]");
            Shtml = HtmlHelper.RemoveNode(Shtml, "//div[@class='noteTA']");
            Shtml = HtmlHelper.RemoveNode(Shtml, "//div[@class='toc']");
            Shtml = HtmlHelper.RemoveNode(Shtml, "//div[@class='notice metadata noprint']");
            Shtml = HtmlHelper.RemoveNode(Shtml, "//table");
            //     Shtml = HtmlHelper.RemoveNode(Shtml, "//table[@class='navbox']");
            //     Shtml = HtmlHelper.RemoveNode(Shtml, "//div[@class]");

            return HtmlHelper.OutText(HtmlHelper.ClearHtml(new Transcoding().HtmlDecodeToUtf8(Shtml)));
        }
    }
}